package com.italicatab;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	private Button btn_submit;
	private NetworkInfo nwinfo;
	private EditText edt_mail,edt_pwd,edt_url;
	private String mail,pwd,url;
 // String URLGroup = "http://"+General.URL+"/api/share/getbusinessgroupid";
	SharedPreferences sp;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		
		
		General.isFrom="";
		
		SharedPreferences sp=getSharedPreferences("Login",1);
		String unm=sp.getString("Username", null);       
		String pass = sp.getString("Password", null);
		String u=sp.getString("Url", null);
		
		if(unm!=null && pass!=null && u!=null)
		{
			//if we have it then no need to stay at this screen just navigate to next screen
//			General.URL=u;
//			General.AppState=null;
			General.Access_Key=null;
			Intent i= new Intent(getApplicationContext(), MainActivity.class);
			startActivity(i);
			this.finish();
			/*edt_mail.setText(unm);
			edt_mail.setSelection(edt_mail.length());
			edt_pwd.setText(pass);
			edt_url.setText(u);*/
		}
		else
		{
			
			edt_mail=(EditText)findViewById(R.id.edt_mail);
			edt_pwd=(EditText)findViewById(R.id.edt_pwd);
			edt_url=(EditText)findViewById(R.id.edt_url);
			
			
			btn_submit = (Button) findViewById(R.id.btn_submit);
			btn_submit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mail=edt_mail.getText().toString().trim();
					pwd=edt_pwd.getText().toString().trim();
					url=edt_url.getText().toString().trim();
					//very temp
					/*mail="maulikkamdar001@gmail.com";
					pwd="mg2772";
					url="ceramicdemo.in";
					*/
					boolean isValid=CheckValidation();
//					if(General.isOnline(LoginActivity.this))
//					{
//						if(isValid){
//							General.URL=url;
//						
//							//temp comment
//								new LoginTask().execute("Login");
//							
//							//Intent i=new Intent(getApplicationContext(), MainActivity.class);
//							//startActivity(i);
//						
//						}
//					}
//					else
//					{
//						Toast.makeText(getApplicationContext(), "Please Check Intenet Connection", Toast.LENGTH_SHORT).show(); 
//					}
				}
			});
		}
		
		
		
		
	}

	
	private class LoginTask extends AsyncTask<String, Integer, String> {

		private ProgressDialog progressDialog;
  private boolean timeout=false;	
		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(LoginActivity.this);
			progressDialog.setMessage("Please Wait...");
			progressDialog.setCancelable(false);
			progressDialog.setIndeterminate(true);
			progressDialog.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			HttpClient httpclient = new DefaultHttpClient();

			//this is in lod project
//			HttpPost httppost = new HttpPost(
//					"http://"+General.URL+"/api/paymentrecovery/checklogin");


		/*	http://ceramicdemo.in/api/paymentrecovery/checklogin;
*/
			
		
			
//			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);
				nameValuePairs.add(new BasicNameValuePair("uname",
						mail));
				nameValuePairs.add(new BasicNameValuePair("upassword",
						pwd));

//				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
//				HttpResponse response = httpclient.execute(httppost);
//				if (response != null) {
				
//					String xml = EntityUtils.toString(response.getEntity());

//					return xml;
//				}
//			}
//				catch (SocketTimeoutException e)
//				{
//					timeout=true;
//				    e.printStackTrace();
//				}
//				catch (ConnectTimeoutException e)
//				{
//					timeout=true;
//				    e.printStackTrace();
//				}
//			 catch (ClientProtocolException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			

			Log.e("MMOS", "response " + result);

			if (result != null ) {
				ManageResponse(result);
			}
			else
			{
				if (timeout) {
		        	Toast.makeText(getApplicationContext(), "Connection TimeOut", Toast.LENGTH_SHORT).show();
					
				}
				else
				{
		        	Toast.makeText(getApplicationContext(), "Invalid Credential", Toast.LENGTH_SHORT).show();
					
				}
	       	 
			}
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			// process the result
			super.onPostExecute(result);
		}

	
	}

	public void ManageResponse(String result) {
		// TODO Auto-generated method stub

		try {
			 String isTrue="";
			XMLParser parser=new XMLParser();
			Document doc = parser.getDomElement(result); // getting DOM element
	        doc.getDocumentElement().normalize();
	       
	        NodeList nl = doc.getElementsByTagName("Output");
	        for (int i = 0; i < nl.getLength(); i++) {
	        	 Element e = (Element) nl.item(i);
	            isTrue = parser.getValue(e, "Result"); // name child value
	            if(isTrue.equals("Success"))
	            {
	            	General.Access_Key=parser.getValue(e, "Accesskey");
	            }
	        }
	        Log.e("casa", "access key  " + General.Access_Key);
	        if(isTrue.equals("Success"))
	        {
	        	SharedPreferences sp=getSharedPreferences("Login", 0);
	        	SharedPreferences.Editor Ed=sp.edit();
	        	Ed.putString("Username",mail);              
	        	Ed.putString("Password",pwd);   
	        	Ed.putString("Url",url);   
	        	Ed.commit();
	        	
	        
	        	//here we will fetch all the contact first in other actiivty
//	        	General.PendingReminder=new ArrayList<HashMap<String,String>>();
	       // 	new GetReminders().execute();
	        Intent i=new Intent(getApplicationContext(), MainActivity.class);
	        	startActivity(i);
	        	this.finish();
	        }
	        else
	        {
	 	        	Toast.makeText(getApplicationContext(), "Invalid Credential", Toast.LENGTH_SHORT).show();
	        }
			
		} catch (Exception e) {
			// TODO: handle exception
	        	Toast.makeText(getApplicationContext(), "Invalid Credential", Toast.LENGTH_SHORT).show();

		}
	}
	
	protected boolean CheckValidation() {
		// TODO Auto-generated method stub
		
		if(mail.length()==0)
		{
			Toast.makeText(getApplicationContext(), "Please Enter Username", Toast.LENGTH_SHORT).show();	
			return false;
		}
		else if(pwd.length()==0)
		{
			Toast.makeText(getApplicationContext(), "Please Enter Password", Toast.LENGTH_SHORT).show();	
			return false;
		}
		else if(url.length()==0)
		{
			Toast.makeText(getApplicationContext(), "Please Enter Url", Toast.LENGTH_SHORT).show();	
			return false;
		}
		else
		{
			return true;
		}
		
	}
	

	
	/*private void SaveList() {
		// TODO Auto-generated method stub
		//as for first time we are setting it to zero
    	SharedPreferences spput=getSharedPreferences("RemainingCount", 0);
    	SharedPreferences.Editor Edt=spput.edit();
    	Edt.putInt("Count", 0);  
    	Edt.commit();
		
		 sp=getSharedPreferences("Login",0);
		int totalCount=0;
		SharedPreferences spget=getSharedPreferences("RemainingCount",1);
		totalCount=spget.getInt("Count", 0);
	//	tv_count.setText(""+totalCount);
		 
		SharedPreferences spRunCountPut=getSharedPreferences("GroupDataSave", 0);
    	SharedPreferences.Editor Edgrp=spRunCountPut.edit();
    	if(General.Access_Key!=null)
    	{
    		Edgrp.putString("AccessKey", General.Access_Key);
    	}
    	if(General.URL==null)
    	{
    		Edgrp.putString("RootUrl", sp.getString("Url", ""));
    	}
    	else
    	{
    		Edgrp.putString("RootUrl", General.URL);
    	}
    	Edgrp.putInt("TotalGroups", General.PendingReminder.size());
    	
		for (int i = 0; i < General.PendingReminder.size(); i++) {
			
			Edgrp.putString("Id_"+i, General.PendingReminder.get(i).get("id"));
			Edgrp.putString("GrpName_"+i, General.PendingReminder.get(i).get("groupname"));
			
		}
    	
    	Edgrp.commit();
			
    	Intent i=new Intent(getApplicationContext(), MainActivity.class);
    	startActivity(i);
    	this.finish();
	}
*/
	
	
	
	
}
